package system.task.tasks;

import framework.exceptions.BusinessException;
import framework.utils.JsonUtil;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;
import system.task.ExecutorContext;
import system.task.Task;
import system.task.TaskExecutor;
import system.task.TaskLogger;

/**
 * 随机任务状态
 */
@Component
public class RandomStatusTask implements TaskExecutor {

    @Override
    public void run(ExecutorContext context) throws Exception {
        Task task = context.getTask();
        TaskLogger logger = context.getLogger();

        int v = RandomUtils.nextInt(1, 5);
        switch (v) {
            case 1:
                context.logError("on abnormal 1");
                return;
            case 2:
                int sleepSec = RandomUtils.nextInt(2, 8) * 1000;
                context.logInfo("SLEEP " + sleepSec);
                Thread.sleep(v);
                break;
            case 3:
                context.logInfo("*** BEGIN: " + task.getName());
                context.logInfo(JsonUtil.toJsonString(task, true));
                context.logInfo("*** END: " + task.getName());
                break;
            case 4:
                throw new BusinessException("Task error 4");
            default:
                context.logInfo("OK");
                break;
        }

        logger.writeln("FINISHED");

    }
}
